package com.star.carservice.client.fragment;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.star.carservice.R;
import com.star.carservice.client.adapter.CarBrandListAdapter;
import com.star.carservice.client.fragment.base.BaseFragment;
import com.star.carserviceapi.domain.CarFeatureInfo;
import com.star.carserviceapi.domain.request.QryCarBrandRequest;
import com.star.carserviceapi.domain.result.QryCarBrandResult;

public class SelectCarBrandFragment extends BaseFragment {

	private final static String TAG = SelectCarBrandFragment.class
			.getSimpleName();

	@Override
	public String getLogTag() {
		return TAG;
	}

	@InjectView(R.id.list_car_brand)
	ListView list_car_brand;
	List<CarFeatureInfo> mData = new ArrayList<CarFeatureInfo>();
	CarBrandListAdapter mAdapter = null;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		execAsyncTask(new QryCarBarnd(), new QryCarBrandRequest());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		if (CacheViewIsNull()) {
			mCacheView = inflater.inflate(R.layout.frag_select_car_brand,
					container, false);

			ButterKnife.inject(this, mCacheView);

			initView();
		}
		
		removeCacheView();

		return mCacheView;
	}

	private void initView() {
		mAdapter = new CarBrandListAdapter(getActivity(), mData);
		list_car_brand.setAdapter(mAdapter);

		list_car_brand.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				CarFeatureInfo item = (CarFeatureInfo) mAdapter
						.getItem(position);

				getActivity()
						.getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.view_placeholder,
								SelectCarSeriesFragment.getInstance(item))
						.addToBackStack(null).commit();

			}
		});
	}

	class QryCarBarnd extends
			AsyncTask<QryCarBrandRequest, Void, QryCarBrandResult> {

		@Override
		protected QryCarBrandResult doInBackground(QryCarBrandRequest... params) {

			return getApi().qryCarBrand(params[0]);
		}

		@Override
		protected void onPostExecute(QryCarBrandResult result) {
			mData.clear();
			mData.addAll(result.getCars());
			mAdapter.notifyDataSetChanged();
		}
	}

}
